package ua.org.nuos.sdms.middle.util.validator;

import org.apache.commons.lang.Validate;
import ua.org.nuos.sdms.middle.entity.EmailVerification;
import ua.org.nuos.sdms.middle.entity.User;
import ua.org.nuos.sdms.middle.util.exception.ExtendedIllegalArgumentException;

import javax.persistence.EntityManager;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: dio
 * Date: 9/1/12
 * Time: 9:29 PM
 * To change this template use File | Settings | File Templates.
 */
public class EmailVerificationValidator extends AbstractValidator<EmailVerification> {

    public EmailVerificationValidator(EntityManager em) {
        super(em);
    }

    @Override
    public void validate(EmailVerification ur) throws IllegalArgumentException {
        Validate.notNull(ur);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set errorSet = validator.validate(ur);
        if (!errorSet.isEmpty()) {
            throw new ExtendedIllegalArgumentException(errorSet);
        }
        Validate.notNull(em.find(User.class, ur.getUser().getId()), "EmailVerification.user is not persist");
    }

    @Override
    public void validatePersisted(EmailVerification ur) throws IllegalArgumentException {
        validate(ur);
    }
}
